Page({
  data: {
    startApplyTime: '',
    endApplyTime: "",
  },

  submit(e) {
    const that = this
    const formValue = e.detail.value
    const newStartTime = that.convertDateTime(formValue.start)
    const newEndTime = that.convertDateTime(formValue.end)
    if (newEndTime && newStartTime && newStartTime < newEndTime) {
      wx.request({
        url: getApp().data.domain + '/setApplyTime',
        method: 'POST',
        data: {
          "startTime": newStartTime,
          "endTime": newEndTime
        },
        success:(res)=>{
          if(res.data.code===0){
            getApp().showMessage('修改成功！')
            that.onLoad()
          }
          else{
            getApp().showMessage('修改失败！')
          }

        },
        fail: res => {
          console.error(res)
        }
      })
    } else {
      getApp().showMessage('请输入正确的时间！')
    }
  },

  onLoad() {
    const that = this;
    //判断身份
    const userInfo = getApp().data.personInfo
    if(userInfo.departmentId != 2 || userInfo.positionName != "1"){
      wx.showModal({
        title: '提示',
        content: '您的权限不足，无法使用本功能',
        complete: (res) => {
          wx.navigateBack()
        }
      })
    }
    //获取信息
    wx.request({
      url: getApp().data.domain + '/getApplyTime',
      method: 'GET',
      success: (res) => {
        const data = res.data.data
        //转换内容
        data.startTime = that.convertDateTime(data.startTime)
        data.endTime = that.convertDateTime(data.endTime)
        that.setData({
          startApplyTime: data.startTime,
          endApplyTime: data.endTime
        })
      }
    })
  },

  convertDateTime(input) {
    // 检查是否为时间戳（毫秒级）  
    if (!isNaN(input) && input.toString().length === 13) {
      // 将时间戳转换为日期，并格式化为 YYYY-MM-DD  
      const date = new Date(parseInt(input, 10));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }

    // 检查是否为 YYYY-MM-DD 格式的日期  
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (dateRegex.test(input)) {
      // 将日期字符串转换为时间戳（时分秒为00:00:00）  
      const [year, month, day] = input.split('-').map(Number);
      const date = new Date(year, month - 1, day); // 月份从0开始  
      return date.getTime();
    }

    // 如果都不是，返回false  
    return false;
  }
})